<template>
  <div class="goods">
    <!-- hello -->
    <el-dialog title="收货地址" :modal="false" :visible.sync="dialogTableVisible">
      <el-table :data="gridData">
        <el-table-column property="goods_id" label="订单id"></el-table-column>
        <el-table-column property="cat_id" label="用户id"></el-table-column>
        <el-table-column property="goods_name" label="订单编号" width="200"></el-table-column>
        <el-table-column property="goods_price" label="权限等级"></el-table-column>
        <el-table-column property="goods_number" label="发货状态"></el-table-column>
        <el-table-column property="goods_weight" label="发货状态"></el-table-column>
        <el-table-column property="add_time" label="发货状态" width="190"></el-table-column>
        <!-- <el-table-column property="pics" label="商品图片" width="190"></el-table-column> -->
      </el-table>
    </el-dialog>

    <!-- 表格头 -->
    <div class="tableHeader">
      <el-input placeholder="请输入内容" class="search" v-model="pId">
        <el-button slot="append" icon="el-icon-search" @click="querypId"></el-button>
      </el-input>
      <span class="mr10"></span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      <router-link to="pcreate">
        <el-button type="btn">添加商品</el-button>
      </router-link>
    </div>

    <!-- /表格头 -->

    <!-- 表格内容 -->
    <div class="tableContent">
      <el-table v-loading="loading" border :data="tableData" stripe style="width: 100%">
        <!-- 
                label 列名称
                width 列宽度
                prop  列填充数据（先不管等接口请求
        -->
        <el-table-column prop="goods_id" label="编号" width="50" align="center" max-height="250"></el-table-column>

        <el-table-column prop="goods_name" label="商品名称" width="680"></el-table-column>

        <el-table-column label="商品价格" width="120" prop="goods_price" align="center"></el-table-column>
        <el-table-column label="商品数量" width="120" prop="goods_number" align="center"></el-table-column>
        <el-table-column label="商品重量" width="120" prop="goods_weight" align="center"></el-table-column>
        <el-table-column label="是否上架" width="120" align="center">
          <template>
            <el-switch></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="是否推荐" width="80" align="center">
          <template>
            <el-switch></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="是否热卖" width="80" align="center">
          <template>
            <el-switch></el-switch>
          </template>
        </el-table-column>

        <el-table-column width="180" fixed="right" label="操作">
          <template slot-scope="scope">
            <!-- scope.row 代表当前行数据 -->
            <!-- <el-button @click="isShowEditTk = true" size="mini" type="danger" icon="el-icon-edit"></el-button> -->
            <el-button @click="editFn(scope.row)" size="mini" type="danger" icon="el-icon-edit"></el-button>
            <el-button
              @click="deleteFn(scope.row.goods_id)"
              size="mini"
              type="info"
              icon="el-icon-delete-solid"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- /表格内容 -->

    <!-- 表格分页 -->
    <div class="tablePage">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage4"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableDataTotal"
      ></el-pagination>
    </div>
    <!-- /表格分页 -->

    <!-- 其他 -->
    <el-dialog
      title="编辑商品"
      :modal="false"
      :visible.sync="isShowEditTk"
      width="30%"
      :before-close="handleClose"
    >
      <el-form label-width="120px">
        <el-form-item label="商品名称">
          <el-input v-model="editFormData.goods_name"></el-input>
        </el-form-item>

        <el-form-item label="商品价格">
          <el-input v-model="editFormData.goods_price"></el-input>
        </el-form-item>

        <el-form-item label="商品数量">
          <el-input v-model="editFormData.goods_number"></el-input>
        </el-form-item>

        <el-form-item label="商品重量">
          <el-input v-model="editFormData.goods_weight"></el-input>
        </el-form-item>

        <el-form-item label="商品分类">
          <el-cascader
            :options="options"
            :props="optionsField"
            v-model="selectedOptions"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
      </el-form>

      <el-upload
        class="upload-demo"
        action="http://localhost:8888/api/private/v1/upload"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :file-list="fileList"
        :headers="setHeaders"
        list-type="picture"
        :on-success="uploadImgFn"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowEditTk = false">取 消</el-button>
        <el-button type="primary" @click="submitFn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- /其他 -->
  </div>
</template>
<script>
// 导入接口
// import  {getGoodsApi} from '@/api/index.js'
import {
  getGoodsApi,
  deleteGoodsApi,
  editGoodsApi,
  getGoodsCateApi,
  querypIdApi
} from "@/api/product";

//
export default {
  mounted() {
    // console.log(1);
    getGoodsCateApi(3).then(res => {
      //   console.log(res);
      this.options = res.data;
    });
  },

  methods: {
    // 编辑
    editFn(row) {
      this.editFormData = {
        goods_name: row.goods_name,
        goods_id: row.goods_id,
        goods_number: row.goods_number,
        goods_weight: row.goods_weight,
        goods_price: row.goods_price,
        pics: []
      };
      // 2. 显示弹框
      this.isShowEditTk = true;
    },
    // 删除
    deleteFn(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 后期会发送异步请求
          deleteGoodsApi(id).then(res => {
            if (res.meta.status == 200) {
              // 1提示
              this.$message.success("删除成功!");
              // 2重新发送异步请求（因为删除成功页面就不需要那一条数据了
              this.initData();
            } else {
              this.$message.error("删除失败!");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 分页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      // 1. 改变模型数据
      this.pagesize = val;
      // 2. 重新发送异步请求
      this.initData();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      // 1. 改变模型数据
      this.pagenum = val;
      // 2. 重新发送异步请求即可
      this.initData();
    },
    // 搜索
    querypId() {
      querypIdApi(this.pId).then(res => {
        console.log(res);
        if (res.meta.status == 201 || res.meta.status == 200) {
          this.gridData.splice(0, 1, res.data);
          this.gridData[0].add_time = this.timeConvert(
            this.gridData[0].add_time,
            1
          );
          this.dialogTableVisible = true;
          this.$message.success("查询成功");
        } else {
          this.$message.error("id不存在，请重新输入");
          this.gridData.splice(0, 1);
          this.dialogTableVisible = false;
        }
      });
    },
    // 上传图片成功触发
    uploadImgFn(response, file, fileList) {
      //   console.log(response);

      // {"pic":"/tmp_uploads/30f08d52c551ecb447277eae232304b8"}
      this.editFormData.pics.push({
        pic: response.meta.status.tmp_path
      });
      console.log(this.editFormData);
    },
    // 表单提交
    submitFn() {
      //   console.log(this.editFormData.pics);
      this.isShowEditTk = false;
      let id = this.editFormData.goods_id;
      let params = {
        goods_id: this.editFormData.goods_id,
        goods_name: this.editFormData.goods_name,
        goods_number: this.editFormData.goods_number,
        goods_weight: this.editFormData.goods_weight,
        goods_price: this.editFormData.goods_price,
        goods_cat: this.editFormData.goods_cat,
        pics: [this.editFormData.pics]
      };
      editGoodsApi(id, params).then(res => {
        if (res.meta.status == 200 || res.meta.status == 201) {
          // 1 提示
          this.initData();
          this.$message.success("修改成功");
          // 2 重新发送异步请求即可
          this.initData();
        } else {
          this.$message.error(res.meta.msg);
        }
      });
    },
    // 弹框
    handleChange(value) {
      this.editFormData.goods_cat = value.join(",");
    },
    handleClose() {
      //   console.log('this is clode')
      this.isShowEditTk = false;
    },
    // 上传图片
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    // 初始化列表数据
    initData() {
      getGoodsApi({
        pagesize: this.pagesize,
        pagenum: this.pagenum,
        query: this.query
      }).then(res => {
        // console.log(res)
        // 数据同步到模型，模型改变同步到视图
        this.tableData = res.data.goods;
        this.tableDataTotal = res.data.total;
      });
    },

    timeConvert(timestamp, num) {
      //num:0 YYYY-MM-DD  num:1  YYYY-MM-DD hh:mm:ss // timestamp:时间戳
      timestamp = timestamp + "";
      timestamp = timestamp.length == 10 ? timestamp * 1000 : timestamp;
      var date = new Date(timestamp);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var h = date.getHours();
      h = h < 10 ? "0" + h : h;
      var minute = date.getMinutes();
      var second = date.getSeconds();
      minute = minute < 10 ? "0" + minute : minute;
      second = second < 10 ? "0" + second : second;
      if (num == 0) {
        return y + "-" + m + "-" + d;
      } else {
        return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
      }
    }
  },
  // 钩子函数
  created() {
    this.initData();
  },
  // 声明模型数据
  data() {
    return {
      pId: "",
      dialogTableVisible: false,
      gridData: [],
      // 设置上传请求头
      setHeaders: {
        Authorization: localStorage.getItem("token")
      },
      // 编辑弹框数据
      editFormData: {
        goods_name: "",
        id: "",
        goods_number: "",
        goods_weight: "",
        goods_price: "",
        pics: [{}]
      },
      // 表格数据
      isShowEditTk: false,
      pagesize: 5,
      pagenum: 1,
      query: "",
      tableDataTotal: 0, // 总数据
      // 表格page
      currentPage1: 5,
      currentPage2: 5,
      currentPage3: 5,
      currentPage4: 1,
      // 表格loading
      loading: false,
      // 表格数据
      tableData: [
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄"
        }
      ],
      // 联级选择器数据
      optionsField: {
        // 声明后期接口获取的数据用哪个字段填充数据
        value: "cat_id",
        label: "cat_name"
      },
      // 联级选择器数据
      options: [
        {
          value: "zhinan",
          label: "指南",
          children: [
            {
              value: "shejiyuanze",
              label: "设计原则",
              children: [
                {
                  value: "yizhi",
                  label: "一致"
                },
                {
                  value: "fankui",
                  label: "反馈"
                },
                {
                  value: "xiaolv",
                  label: "效率"
                },
                {
                  value: "kekong",
                  label: "可控"
                }
              ]
            },
            {
              value: "daohang",
              label: "导航",
              children: [
                {
                  value: "cexiangdaohang",
                  label: "侧向导航"
                },
                {
                  value: "dingbudaohang",
                  label: "顶部导航"
                }
              ]
            }
          ]
        },
        {
          value: "zujian",
          label: "组件"
        },
        {
          value: "ziyuan",
          label: "资源",
          children: [
            {
              value: "axure",
              label: "Axure Components"
            },
            {
              value: "sketch",
              label: "Sketch Templates"
            },
            {
              value: "jiaohu",
              label: "组件交互文档"
            }
          ]
        }
      ],
      selectedOptions: [],
      selectedOptions2: [],
      // 联级选择器结束

      // 上传图片
      fileList: [
        // {name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}
      ]
    };
  }
};
</script>
<style lang="scss" scoped>
// goods
.goods {
  width: 96%;
  margin: auto;
  height: 100%;
  overflow: hidden;

  // tableHeader
  .tableHeader {
    width: 100%;
    padding: 10px 0px;
    background: #fff;

    // search
    .search {
      width: 300px;
    }
  }

  // tableContent
  .tableContent {
    margin: 10px 0px;
  }
  // tablePage
  .tablePage {
    width: 100%;
    padding: 10px 0px;
    background: #fff;
  }
}
</style>